package utils

import (
	"software/global"
	"software/models"
	"time"
)

func StartBanCheckTask() {
	ticker := time.NewTicker(1 * time.Hour) // 每小时检查一次
	defer ticker.Stop()

	for range ticker.C {
		var users []models.User
		now := time.Now()

		// 查询所有未解封的用户
		result := global.DB.Where("ban_time IS NOT NULL AND ban_time < ?", now).Find(&users)
		if result.Error != nil {
			global.Log.Error("查询封禁用户失败:", result.Error)
			continue
		}

		// 解封用户并更新状态
		for _, user := range users {
			updateResult := global.DB.Model(&user).Updates(map[string]interface{}{
				"ban_time": nil,
				"Status":   1, // 更新状态为正常
			})
			if updateResult.Error != nil {
				global.Log.Errorf("解封用户 %s 失败: %v\n", user.Nickname, updateResult.Error)
				continue
			}
			global.Log.Infof("用户 %s 已自动解封，状态已更新\n", user.Nickname)
		}
	}
}
